package com.cyzy.service.impl;

import com.cyzy.service.DistributedLockService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * 分布式锁服务实现
 */
@Slf4j
@Service
public class DistributedLockServiceImpl implements DistributedLockService {
    
    @Autowired
    private RedissonClient redissonClient;
    
    @Override
    public <T> T executeWithLock(String lockKey, long waitTime, long leaseTime, TimeUnit timeUnit, Supplier<T> supplier) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            // 尝试获取锁
            boolean acquired = lock.tryLock(waitTime, leaseTime, timeUnit);
            if (!acquired) {
                log.warn("获取分布式锁失败, lockKey: {}", lockKey);
                throw new RuntimeException("系统繁忙，请稍后重试");
            }
            
            log.info("成功获取分布式锁, lockKey: {}", lockKey);
            // 执行业务逻辑
            return supplier.get();
            
        } catch (InterruptedException e) {
            log.error("获取分布式锁被中断, lockKey: {}", lockKey, e);
            Thread.currentThread().interrupt();
            throw new RuntimeException("系统繁忙，请稍后重试");
        } finally {
            // 释放锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
                log.info("释放分布式锁, lockKey: {}", lockKey);
            }
        }
    }
    
    @Override
    public <T> T executeWithLock(String lockKey, Supplier<T> supplier) {
        // 默认等待3秒，持有锁10秒
        return executeWithLock(lockKey, 3, 10, TimeUnit.SECONDS, supplier);
    }
} 